import { NextResponse } from 'next/server';
import User from '@/models/user';
import bcrypt from 'bcrypt';

// 获取单个用户
export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const user = await User.findByPk(id);
    if (!user) {
      return NextResponse.json({ code: 404, msg: '用户不存在' }, { status: 404 });
    }
    return NextResponse.json({ code: 0, data: user, msg: '获取用户成功' });
  } catch (error) {
    console.error('获取用户失败:', error);
    return NextResponse.json({ code: 500, msg: '获取用户失败' }, { status: 500 });
  }
}

// 更新用户
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const data = await request.json();
    const { id } = await params;
    const user = await User.findByPk(id);
    if (!user) {
      return NextResponse.json({ code: 404, msg: '用户不存在' }, { status: 404 });
    }
    
    // 如果提供了密码，需要进行加密
    const updateData = { ...data };
    if (updateData.password_hash) {
      const saltRounds = 10;
      updateData.password_hash = await bcrypt.hash(updateData.password_hash, saltRounds);
    } else {
      // 如果没有提供密码，不更新密码字段
      delete updateData.password_hash;
    }
    
    await user.update(updateData);
    return NextResponse.json({ code: 0, data: user, msg: '更新用户成功' });
  } catch (error) {
    console.error('更新用户失败:', error);
    return NextResponse.json({ code: 500, msg: '更新用户失败' }, { status: 500 });
  }
}

// 删除用户
export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const user = await User.findByPk(id);
    if (!user) {
      return NextResponse.json({ code: 404, msg: '用户不存在' }, { status: 404 });
    }
    await user.destroy();
    return NextResponse.json({ code: 0, msg: '删除用户成功' });
  } catch (error) {
    console.error('删除用户失败:', error);
    return NextResponse.json({ code: 500, msg: '删除用户失败' }, { status: 500 });
  }
}